import importlib
import subprocess
import sys

class StockProcessor:
    def __init__(self):
        self.modules = {
            1: ("jye", "process"),
            2: ("stock_rank_cxg", "process"),
            3: ("stock_rank_ljqs", "process"),
            4: ("zjlx", "process"),
            5: ("ztbxxfx", "process"),
            6: ("bmlc_dxf", "process"),
            7: ("stockMoneyData", "process")
        }

    def show_menu(self):
        """显示功能菜单"""
        print("请选择要执行的功能：")
        print("1. 地区交易数据转换")
        print("2. 创新高股票排名")
        print("3. 量价齐升股票")
        print("4. 资金流向分析")
        print("5. 涨停板信息分析")
        print("6. 大消费/白马蓝筹低位补涨")
        print("7. 获取财报数据")
        print("0. 退出程序")

    def execute(self, choice):
        """执行对应功能"""
        if choice not in self.modules and choice != 0:
            raise ValueError("无效的选择")

        if choice == 0:
            print("程序已退出")
            sys.exit()

        module_name, func_name = self.modules[choice]
        try:
            module = importlib.import_module(module_name)
            getattr(module, func_name)()
            print(f"{module_name} 执行完成")
        except Exception as e:
            print(f"执行出错: {str(e)}")
            import traceback
            traceback.print_exc()

    def install_or_update_akshare(self):
        """安装或更新 akshare 库"""
        print("检查并更新 akshare 库...")
        try:
            # 尝试导入 akshare 来检查是否已安装
            import akshare
            print("akshare 库已存在，正在执行更新...")
        except ImportError:
            print("akshare 库未安装，正在进行安装...")

        try:
            # 执行更新操作（无论是否已安装都会执行更新）
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", "akshare",
                "--upgrade", "-i", "https://pypi.org/simple"
            ])
            print("akshare 库更新完成")
        except subprocess.CalledProcessError as e:
            print(f"更新失败: {e}")
            sys.exit(1)

if __name__ == "__main__":
    #启动前执行命令 pip install akshare --upgrade -i https://pypi.org/simple

    print("欢迎使用股票数据处理程序")

    processor = StockProcessor()
    # 自动安装 akshare 库
    # processor.install_or_update_akshare()

    while True:
        processor.show_menu()
        try:
            choice = int(input("请输入选项数字（0-7）: "))
            if choice == 0:
                processor.execute(0)
            elif 1 <= choice <= 7:
                processor.execute(choice)
            else:
                print("输入超出范围，请重新输入")
        except ValueError:
            print("无效输入，请输入数字")
        print("\n" + "="*40 + "\n")
